import 'dart:convert';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/common_utils.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../entity/banner_for_home_entity.dart';
import '../entity/stock_lines_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/double_utils.dart';
import '../utils/user_utils.dart';

///
/// 交易首页-股票行情
///
class HomeMarketStock extends StatefulWidget {
  HomeMarketStock({Key? key}) : super(key: key);

  @override
  State<HomeMarketStock> createState() => _HomeMarketStockState();
}

class _HomeMarketStockState extends State<HomeMarketStock> {
  String imgUrl = '';
  String name = '';
  String price = '0';
  String change = '0';
  String changeStr = '';
  Color changeColor = Colors.green;

  //轮播
  List<BannerForHomeData> banners = [];

  List<StockLinesData> stockDataLines = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBannerList();
    getSevenPrice();
    getData();
  }

  getBannerList() async {
    dynamic result = await Api.bannerForHome({'type': 'trade'});
    BannerForHomeEntity entity = BannerForHomeEntity.fromJson(result);
    setState(() {
      banners.clear();
      banners.addAll(entity.data);
      // Future.delayed(const Duration(milliseconds: 1500), () {
      //   setState(() {
      //     isLoopBanner = true;
      //   });
      // });
    });
  }

  getSevenPrice() async {
    dynamic result = await Api.candlestick();
    StockLinesEntity entity = StockLinesEntity.fromJson(result);
    setState(() {
      stockDataLines = entity.data;
      // for (int i = 0; i < stockDataLines.length; i++) {
      //   stockDataLines[i].price = Random().nextDouble().toString();
      // }
    });
  }

  getData() async {
    dynamic result = await Api.stockInfo();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      setState(() {
        imgUrl = jsonResult['data']['image'];
        name = jsonResult['data']['name'];
        price = jsonResult['data']['current_price'];
        change = jsonResult['data']['price_change_percentage_24h'];

        double cha = double.parse(change);
        if (cha > 0) {
          changeStr = '+${DoubleUtils.formartNum(cha, 2)}%';
          changeColor = Colors.green;
        } else {
          changeStr = '${DoubleUtils.formartNum(cha, 2)}%';
          changeColor = Colors.red;
        }
      });
    }
  }

  getListItem() {
    return Container(
      height: 110.w,
      margin: EdgeInsets.symmetric(horizontal: 0.w, vertical: 0.w),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Config.colorDivider, width: 2.w),
        ),
      ),
      child: InkWell(
        onTap: () {},
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 5.w, right: 12.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(24.w),
                      child: CachedNetworkImage(
                        imageUrl: imgUrl,
                        fit: BoxFit.fill,
                        width: 48.w,
                        height: 48.w,
                        placeholder: (context, str) {
                          return Image.asset(
                            'assets/images/bg_default_400.png',
                            width: 44.w,
                            height: 44.w,
                            fit: BoxFit.fill,
                          );
                        },
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/bg_default_400.png',
                            width: 48.w,
                            height: 48.w,
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      name,
                      softWrap: false,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: (Config.colorText1), fontSize: 28.w),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  price,
                  softWrap: false,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: (Config.colorText1), fontSize: 28.w),
                ),
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                    alignment: Alignment.center,
                    height: 40.w,
                    width: 120.w,
                    decoration: BoxDecoration(
                      color: changeColor,
                      borderRadius: BorderRadius.all(
                        Radius.circular(10.w),
                      ),
                    ),
                    child: Text(
                      changeStr,
                      softWrap: false,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: (Config.colorWhite), fontSize: 20.w),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 25.w),
        // decoration: BoxDecoration(
        //   borderRadius: BorderRadius.circular(12.w),
        // ),
        child: EasyRefresh.builder(
          header: const MaterialHeader(),
          footer: const MaterialFooter(),
          onRefresh: () async {
            await Future.delayed(const Duration(milliseconds: 200), () {
              getBannerList();
              getSevenPrice();
              getData();
            });
          },
          // onLoad: () async {},
          childBuilder: (context, physics) {
            return ListView(
              scrollDirection: Axis.vertical,
              physics: physics,
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.w, bottom: 20.w),
                  //轮播
                  height: 300.w,
                  child: Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return ClipRRect(
                        borderRadius: BorderRadius.circular(12.w),
                        child: CachedNetworkImage(
                          imageUrl: CommonUtils.compressImageUrl(banners[index].imgPath, 750, 350),
                          fit: BoxFit.fill,
                          width: double.infinity,
                          height: double.infinity,
                          errorWidget: (context, url, error) {
                            return Image.asset(
                              'assets/images/bg_default_400.png',
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.fill,
                            );
                          },
                        ),
                      );
                    },
                    onTap: (index) {},
                    autoplayDelay: 4000,
                    autoplay: true,
                    loop: true,
                    layout: SwiperLayout.DEFAULT,
                    itemCount: banners.length,
                    // viewportFraction: 0.7,
                    // scale: 0.8,
                    pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          // size: Size(20.w, 4.w),
                          // activeSize: Size(20.w, 4.w),
                          size: 15.w,
                          activeSize: 15.w,
                          activeColor: Config.colorMain,
                          color: Config.colorWhite),
                    ),
                  ),
                ),
                Container(
                  height: 50.w,
                  margin: EdgeInsets.only(top: 0.w),
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () {},
                        child: Text(
                          '股票行情',
                          style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(
                  height: 30.w,
                  thickness: 2.w,
                  color: Config.colorDivider,
                ),
                Container(
                  height: 60.w,
                  margin: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Text(
                          '股票名称',
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          '最新价格',
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          '24H涨跌幅',
                          textAlign: TextAlign.right,
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                    ],
                  ),
                ),
                Column(
                  children: [
                    ListView.builder(
                      itemCount: 1,
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return getListItem();
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 25.w),
                      height: 300.w,
                      width: double.infinity,
                      child: SfCartesianChart(
                        primaryXAxis: CategoryAxis(
                          isVisible: true,
                          opposedPosition: false,
                          isInversed: false,
                          labelStyle: const TextStyle(color: Config.colorText1),
                        ),
                        selectionType: SelectionType.series,
                        isTransposed: false,
                        selectionGesture: ActivationMode.singleTap,
                        series: <SplineSeries<StockLinesData, String>>[
                          SplineSeries(
                            dataSource: stockDataLines,
                            xValueMapper: (StockLinesData data, _) =>
                                data.data.substring(5, data.data.length),
                            yValueMapper: (StockLinesData data, _) => double.parse(data.price),
                            dataLabelSettings: const DataLabelSettings(
                              isVisible: true,
                            ),
                            markerSettings: const MarkerSettings(isVisible: true),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ],
            );
          },
        ),
      ),
      bottomNavigationBar: Container(
        width: double.infinity,
        height: 200.w,
        padding: EdgeInsets.symmetric(vertical: 60.w, horizontal: 200.w),
        child: ElevatedButton(
          clipBehavior: Clip.antiAlias,
          onPressed: () async {
            if (await UserUtils.isLogin() == false) {
              EasyLoading.showToast('请先登录');
              return;
            }
            Routes.navigateTo(context, Routes.mineStockExchange);
          },
          style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
          child: Text('前往兑换', style: TextStyle(fontSize: 28.sp)),
        ),
      ),
    );
  }
}

class PriceData {
  PriceData(this.data, this.price);

  final String data;
  final double price;
}
